﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Atmk.WaterMeter.MIS.Entities.Enums;
using Newtonsoft.Json;

namespace Atmk.WaterMeter.MIS.Entities.Common
{
    /// <summary>
    /// 数据库记录（实体）的基础属性
    /// </summary>
    public abstract class BaseRecord : IRecord
    {
        protected BaseRecord()
        {
            //if (Id.ToString() != Guid.Empty.ToString()) return;
            //Id = Guid.NewGuid();
            if (Id != null) return;
            Id = Guid.NewGuid().ToString();
            RecordState = RecordStateEnum.Normal;
            CreateTime = DateTime.Now;
            Log = JsonConvert.SerializeObject(new List<RecordLog> {new RecordLog("system", DateTime.Now, "Init")});
        }

        /// <summary>
        /// 实体ID
        /// </summary>
        public string Id { get; set; }

        /// <summary>
        /// 实体的不常用属性。以JSON序列化格式进行存储。
        /// </summary>
        public string Memo { get; set; }

        /// <summary>
        /// 实体的修改记录。以JSON序列化格式进行存储。
        /// </summary>
        public string Log { get; private set; }

        [Display(Name = "记录创建时间"), Required(ErrorMessage = "{0}不能为空"), DataType(DataType.DateTime, ErrorMessage = "时间格式错误")]
        public DateTime CreateTime { get; set; }

        public void ModifiedLog(string user, string annotation = "") => AddModifiedLog(user, annotation);

        /// <inheritdoc />
        /// <summary>
        /// 记录状态
        /// </summary>
        [Required]
        public RecordStateEnum RecordState { get; set; }

        /// <summary>
        /// 添加记录操作信息
        /// </summary>
        /// <param name="user">记录者</param>
        /// <param name="annotation">注释,注解</param>
        private void AddModifiedLog(string user, string annotation = "")
        {
            var logs = new List<RecordLog>();
            if (Log!=null)
                logs = JsonConvert.DeserializeObject<List<RecordLog>>(Log);
            logs.Add(new RecordLog(user, DateTime.Now, annotation));
            Log = JsonConvert.SerializeObject(logs);
        }
    }
}
